package cv.vender;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.telephony.TelephonyManager;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TimeZone;

public class clsToolBox {

    static short s(byte[] b) {
        return (short) (((b[1] & 0x000000FF) << 8) | (0x000000FF & b[0]));
    }

    static short little_byte2short(byte[] b, int startindex) {
        return (short) (((b[startindex + 1] & 0x000000FF) << 8) | (0x000000FF & b[startindex]));
    }

    static short big_byte2short(byte[] b) {
        return (short) (((b[0] & 0x000000FF) << 8) | (0x000000FF & b[1]));

    }


    /**
     * 基于位移的int转化成byte[]
     *
     * @param number 将要转换的数字
     * @return
     */
    public static byte[] intToByte(int number) {
        byte[] abyte = new byte[4];
        // "&" 与（AND），对两个整型操作数中对应位执行布尔代数，两个位都为1时输出1，否则0。
        abyte[0] = (byte) (0xff & number);
        // ">>"右移位，若为正数则高位补0，若为负数则高位补1
        abyte[1] = (byte) ((0xff00 & number) >> 8);
        abyte[2] = (byte) ((0xff0000 & number) >> 16);
        abyte[3] = (byte) ((0xff000000 & number) >> 24);
        return abyte;
    }

    /**
     * 取得时间字符串，形如：20090831150534
     *
     * @param date 日期
     * @return 返回形如"yyyyMMddHHmmss"的字符串
     */
    public static String getTimeLongString(java.util.Date date) {
        String TemString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone timezone = TimeZone.getTimeZone("Asia/Shanghai");
        sdf.setTimeZone(timezone);
        TemString = sdf.format(date);
        return TemString;
    }

    /**
     * 基于位移的int转化成byte[]
     *
     * @param number 将要转换的数字
     * @param abyte  目标数组
     * @param index  存储起始索引
     * @return
     */
    public static int intToByte(int number, byte[] abyte, int index) {
        // "&" 与（AND），对两个整型操作数中对应位执行布尔代数，两个位都为1时输出1，否则0。
        abyte[index++] = (byte) (0xff & number);
        // ">>"右移位，若为正数则高位补0，若为负数则高位补1
        abyte[index++] = (byte) ((0xff00 & number) >> 8);
        abyte[index++] = (byte) ((0xff0000 & number) >> 16);
        abyte[index++] = (byte) ((0xff000000 & number) >> 24);
        return index;
    }


    /**
     * @param number
     * @param abyte
     */
    public static int shortToByte(short number, byte[] abyte, int index) {
        // "&" 与（AND），对两个整型操作数中对应位执行布尔代数，两个位都为1时输出1，否则0。
        abyte[index++] = (byte) (0xff & number);
        // ">>"右移位，若为正数则高位补0，若为负数则高位补1
        abyte[index++] = (byte) ((0xff00 & number) >> 8);

        return index;
    }


    public static int longToByte(long number, byte[] abyte, int index) {
        abyte[index++] = (byte) (0xff & number);
        // ">>"右移位，若为正数则高位补0，若为负数则高位补1
        abyte[index++] = (byte) ((0xff00 & number) >> 8);
        abyte[index++] = (byte) ((0xff0000 & number) >> 16);
        abyte[index++] = (byte) ((0xff000000 & number) >> 24);
        abyte[index++] = (byte) ((0xff00000000l & number) >> 32);
        abyte[index++] = (byte) ((0xff0000000000l & number) >> 40);
        abyte[index++] = (byte) ((0xff000000000000l & number) >> 48);
        abyte[index++] = (byte) ((0xff00000000000000l & number) >> 56);
        return index;
    }

    /**
     * 基于位移的 byte[]转化成int
     *
     * @param bytes
     * @return number
     */

    public static int little_byte2int(byte[] bytes) {
        int number = bytes[0] & 0xFF;
        // "|="按位或赋值。
        number |= ((bytes[1] << 8) & 0xFF00);
        number |= ((bytes[2] << 16) & 0xFF0000);
        number |= ((bytes[3] << 24) & 0xFF000000);
        return number;
    }


    /**
     * 利用 {@link java.nio.ByteBuffer}实现byte[]转long
     *
     * @param input
     * @param offset
     * @param 、、littleEndian 输入数组是否小端模式
     * @return
     */
    public static long little_byte2long(byte[] input, int offset) {
        if (offset < 0 || offset + 8 > input.length)
            throw new IllegalArgumentException(String.format("less than 8 bytes from index %d  is insufficient for long", offset));
        ByteBuffer buffer = ByteBuffer.wrap(input, offset, 8);
        buffer.order(ByteOrder.LITTLE_ENDIAN);

        return buffer.getLong();
    }


    /**
     * 基于位移的 byte[]转化成int
     *
     * @param bytes
     * @param index
     * @return
     */
    public static int little_byte2int(byte[] bytes, int index) {
        int number = bytes[index + 0] & 0xFF;
        // "|="按位或赋值。
        number |= ((bytes[index + 1] << 8) & 0xFF00);
        number |= ((bytes[index + 2] << 16) & 0xFF0000);
        number |= ((bytes[index + 3] << 24) & 0xFF000000);
        return number;
    }

    public static Calendar ParseDateString(String datestring) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

        java.util.Date date;
        Calendar c = Calendar.getInstance();
        try {
            date = sdf.parse(datestring);
            c.setTimeInMillis(date.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return c;
    }


    /**
     * 基于位移的 byte[]转化成int
     *
     * @param bytes
     * @return int  number
     */

    public static int big_byte2int(byte[] bytes) {
        int number = bytes[3] & 0xFF;
        // "|="按位或赋值。
        number |= ((bytes[2] << 8) & 0xFF00);
        number |= ((bytes[1] << 16) & 0xFF0000);
        number |= ((bytes[0] << 24) & 0xFF000000);
        return number;
    }

    public static int ParseInt(String str_sid) {
        try {
            return Integer.parseInt(str_sid);
        } catch (Exception e) {
            // TODO: handle exception
            return 0;
        }

    }

    /**
     * 将一个asc数据流转化成一个字符串
     *
     * @param b
     * @param start_index
     * @return
     */
    public static String AscByte2StringTerminalByNull(byte[] b, int start_index) {
        if (b == null) {
            return "";
        }
        int end_index = start_index;
        for (; end_index < b.length; end_index++) {
            if (b[end_index] == 0) {
                break;
            }
        }


        try {
            return new String(b, start_index, end_index - start_index, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * 将一个asc数据流转化成一个字符串
     *
     * @param b
     * @param start_index
     * @return
     */
    public static String AscByte2StringByEndIndex(byte[] b, int start_index, int end_index) {
        if (b == null) {
            return "";
        }

        try {
            return new String(b, start_index, end_index - start_index, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return "";
    }

    public static String BytesToHexString(byte[] b, int len) {
        int i;
        StringBuilder out = new StringBuilder();
        for (i = 0; i < len; i++) {
            out.append(String.format("%02X,", b[i]));
        }
        return out.toString();
    }

    public static void printX(byte x) {
        System.out.print(String.format("%02X,", x));
    }

    public static void printX(byte[] b, int len) {
        int i;
        for (i = 0; i < len; i++) {
            printX(b[i]);
        }
        System.out.println();
    }

    /**
     * 取得日期时间字符串，形如：2009-8-31 16:11:03
     *
     * @return 日期时间字符串，形如：2009-08-31 16:11:03
     */
    public static String getDateTimeString() {
        String TemString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //TimeZone timezone = TimeZone.getTimeZone("Asia/Shanghai");
        //sdf.setTimeZone(timezone);
        TemString = sdf.format(new java.util.Date(System.currentTimeMillis()));
        return TemString;
    }

    /**
     * @return 返回RPID；形如090903104822XXXX
     */
    public static String MakeRPID() {
        String TemStr = String.format("%04d", (int) (Math.random() * 10000));
        return getTimeString() + TemStr;
    }

    /**
     * 取得时间字符串，形如：20090831150534
     *
     * @return 返回形如"yyyyMMddHHmmss"的字符串
     */
    public static String getTimeString() {
        return getTimeString(new java.util.Date());
    }

    /**
     * 取得时间字符串，形如：20090831150534
     *
     * @return 返回形如"yyyyMMddHHmmss"的字符串
     */
    public static String getTimeString(java.util.Date date) {
        String TemString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        TimeZone timezone = TimeZone.getTimeZone("Asia/Shanghai");
        sdf.setTimeZone(timezone);
        TemString = sdf.format(date);
        return TemString;
    }

    /**
     * 获取外置SD卡路径
     *
     * @return 应该就一条记录或空
     */
    public static ArrayList<String> getExtSDCardPath() {
        ArrayList<String> lResult = new ArrayList<String>();
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains("external_sd")) {
                    String[] arr = line.split(" ");
                    String path = arr[1];
                    File file = new File(path);
                    if (file.isDirectory()) {
                        lResult.add(path);
                    }
                }
            }
            isr.close();
        } catch (Exception e) {
        }
        return lResult;
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            //versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            //Log.e("VersionInfo", "Exception", e);
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 加载本地图片
     *
     * @param file
     * @return
     */
    public static Bitmap getLoacalBitmap(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static long ParseLong(String str_sid) {
        try {
            return Long.parseLong(str_sid);
        } catch (Exception e) {
            // TODO: handle exception
            return 0;
        }
    }

    /**
     * 读取本地文件中的字符串
     *
     * @param url 文件地址,绝对路径
     * @return 字符串列表
     */
    public static ArrayList<String> ReadStringFromFile(String url) {
        //String str=null;
        if (!new File(url).exists()) {
            //System.out.println("没有文件需要发送");
            return null;
        }
        ArrayList<String> lst = new ArrayList<>();
        try {
            FileInputStream fis = new FileInputStream(url);
            InputStreamReader isp = new InputStreamReader(fis, "GBK");
            BufferedReader br = new BufferedReader(isp);
            String line = null;
            while ((line = br.readLine()) != null) {
                //str=line;
                lst.add(line);
            }
            br.close();
            isp.close();
            fis.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lst;
    }

    public static void SaveStringToFile(String str, String url, boolean append) {
        try {
            FileOutputStream fos = new FileOutputStream(url, append);
            BufferedOutputStream out = new BufferedOutputStream(fos);
            out.write(str.getBytes("GBK"));
            out.flush();
            out.close();

        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void println(String str) {
        if (str != null) {
            System.out.println(str);
        } else {
            System.out.println("NULL");
        }
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    //System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            //System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }

    }

    public static void DeleteFile(String f1) {
        try {
            File file = new File(f1);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    private String GetImeiId(Context context) {
        String Imei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
        return Imei;
    }


}
